import http from 'wechat-http'
http.baseURL = 'https://live-api.itheima.net'
http.intercept.response = async ({
  config,
  data,
  statusCode
}) => {
  // console.log(statusCode);
  if (statusCode === 401) {
    if (config.url.includes('/refreshToken')) {
      // 读取当前的页面栈
      const pageStack = getCurrentPages()
      // 取出当前的页面路径，登录成功之后跳转到这个页面
      const lastPage = pageStack[pageStack.length - 1]
      const redirectURL = lastPage.route
      wx.redirectTo({
        url: `/pages/login/index?redirectURL=/${redirectURL}`,
      })
      return
    }
    if (!getApp().refresh_token) {

      Promise.reject(new Error('未登录'))
      const pagesStack = getCurrentPages()
      const lastPage = pagesStack[pagesStack.length - 1]
      const redirectURL = lastPage.route
      wx.redirectTo({
        url: `/pages/login/index?redirectURL=/${redirectURL}`,
      })
      return
    }
    if (statusCode === 500) {
      const pagesStack = getCurrentPages()
      const lastPage = pagesStack[pagesStack.length - 1]
      const redirectURL = lastPage.route
      wx.redirectTo({
        url: `/pages/login/index?redirectURL=${redirectURL}`,
      })
      return

    }

    const app = getApp()
    const res = await http({
      url: '/refreshToken',
      method: 'post',
      header: {
        Authorization: app.refresh_token
      }
    })
    // console.log(res);
    // 保存token
    app.setToken(res.data.token, res.data.refreshToken)

    // 无感刷新
    return http(
      Object.assign(config, {
        header: {
          Auxthorization: app.token
        }
      })
    )
    // is refresh_token
  }


  // console.log(config);

  return data
}
// 请求拦截器
http.intercept.request = (config) => {
  const {
    token
  } = getApp()
  // 管理所有额外的属性的对象
  const defaultHeader = {
    client: 'app'
  }
  if (token) {
    defaultHeader.Authorization = token
  }
  // 合并
  config.header = Object.assign(defaultHeader, config.header)
  return config


}
wx.http = http
export default http